const express = require('express')
const route = express.Router()
const Wxsuser = require('../../models/Wxsuser')
const Wxquestion = require('../../models/Wxquestion')
const Wxsquestion = require('../../models/Wxsquestion')
const Wxsask = require('../../models/Wxsask')
const Wxscomment = require('../../models/Wxscomment')
const axios = require('axios')
const { rawListeners } = require('../../models/Wxsuser')
const fs = require('fs')
const path = require('path')

module.exports = (app) => {
    // 根据用户code，从微信服务器获取用户的openid, 查看数据库中是否有用户数据，有就获取到, 没有就新建用户数据， 并把用户对象放到req上（）用户对象为mongoose文档
    async function openid(req, res, next){
        if(req.body.type == 'code'){
            let url = `https://api.weixin.qq.com/sns/jscode2session?appid=wxd2b7b5c50ebcaee2&secret=2117f238c934b2f67af06bc45d419148&js_code=${req.body.code}&grant_type=authorization_code`
            const wxresult = await axios.get(url)
            if(!wxresult.data.openid){res.send({status: 200, message: 'code无效'})}
            let user = await Wxsuser.findOne({openid: wxresult.data.openid})
            // 没有找到用户，新建用户
            if(!user){
                const result = await Wxsuser.create({openid: wxresult.data.openid})
                user = result
            }
            req.user = user
        }else{
            let user = await Wxsuser.findOne({openid: req.body.code})
            req.user = user
        } 
        next()
    }

    //  查找用户questions数据，没有就初始化一个用户questions数据,接收用户数据和用户所选模式参数, 返回用户questions， 是一个mongoose query对象。
    async function noIsCreate(user, model){
        let userQuestion = await Wxsquestion.findOne({openid: user.openid, chexing: user.chexing, kemu: user.kemu, model: model})
        if(!userQuestion){
            let questions = (await Wxquestion.findOne({chexing: user.chexing}))[user.kemu]
            userQuestion = await Wxsquestion.create({
                openid: user.openid,
                chexing: user.chexing,
                kemu: user.kemu,
                model: model,
                questions: questions
            })
        }
        return userQuestion
    }
    // 用户进入小程序，需要获取到用户的基础数据
    route.post('/', async (req, res) => {
        const userQuestion = await noIsCreate(req.user, 'shunxu')
        const user = req.user.toObject()
        user.currentJindu = userQuestion.jindu
        user.studyJindu = userQuestion.studyJindu
        user.total = userQuestion.questions.length
        res.send({statusCode:200, user:user})
    })
    // 修改用户车型、科目
    route.post('/changechexing/:model/:content', async (req, res) => {
        await Wxsuser.findByIdAndUpdate(req.user._id, {[req.params.model]: req.params.content})
        res.send({status:200, [req.params.model]: req.params.content})
    })
    // 获取题目数据
    route.post('/getquestions/:model', async (req, res) => {
        console.log('收到客户端的请求了')
        let userQuestion = await Wxsquestion.findOne({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: req.params.model})
        if(req.params.model == 'moni'){
            await Wxsquestion.findOneAndRemove({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: req.params.model})
            // moni 测试  随机找出100个问题
            userQuestion = await noIsCreate(req.user, req.params.model)
            userQuestion = await Wxsquestion.findOne({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: req.params.model})
            userQuestion.questions.sort(()=>Math.random() - 0.5)
            userQuestion.questions.splice(100)
            await userQuestion.save()

        }
        // 学习模式
        if(req.params.model == 'study'){
            userQuestion = await Wxsquestion.findOne({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'shunxu'})
            const questions = (await Wxquestion.findOne({chexing: req.user.chexing}))[req.user.kemu]
            // 如果用户还没有建立自己的顺序题库
            if(!userQuestion){userQuestion = await noIsCreate(req, 'shunxu')}

            userQuestion.toObject()
            questions.map((item, index) => {
                item.answer.split('').map(temp => {
                    if(temp == '对'){temp = 'Y'}
                    if(temp == '错'){temp = 'N'}
                    item[`active${temp}`] = 'active right'
                })
                item.candianji = false
                item.showAnswer = true
                item.shoucang = userQuestion.questions[index].shoucang
            })
            userQuestion.questions = questions
        }
        if(req.params.model == 'yicuo'){
            // 如果易错题库没有题目。或者没有易错题库
            if(!userQuestion || userQuestion.questions.length == 0){res.send({status: 200, userQuestion:{message:'暂无错题'}})}
        }
        console.log('即将发送数据......')
        res.send({status:200, userQuestion})
    })
    // 初始化用户题目数据
    route.post('/initquestions/:model', async (req, res) => {
        let questions = (await Wxquestion.findOne({chexing: req.user.chexing}))[req.user.kemu]
        const userQuestion = await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: req.params.model}, {
            questions: questions,
            righttotal : 0,
            errtotal : 0,
            jindu : 0
        }, {new: true})
        res.send({status:200, userQuestion})
    })
    // 上传用户自己的选项、答案到用户自己对应的题库
    route.post('/updateuserquestion/:jindu/:model', async (req, res) => {
        const timu = await Wxsquestion.findOne({
            openid: req.user.openid, 
            chexing: req.user.chexing, 
            kemu: req.user.kemu, 
            model: req.params.model
        })
        const arr = timu.toObject().questions
        arr[req.params.jindu] = req.body.question
        const result = await Wxsquestion.findOneAndUpdate({
            openid: req.user.openid, 
            chexing: req.user.chexing, 
            kemu: req.user.kemu, 
            model: req.params.model
        },{questions: arr})
        // 如果用户题目答错，把错题放入用户自己的错题库，如果没有错题库就新建一个
        if(req.body.question.useranswer != req.body.question.answer){
            // 寻找错题库 没有找到就新建一个
            const yicuo = await collectionTitle(req)
            // 如果正在易错界面，就不添加易错题目
            if(req.params.model != 'yicuo'){
                yicuo.toObject()
                // 如果错题库中已经存在该题目，就不添加
                const index = yicuo.questions.findIndex(item => item.questionId == req.body.question.questionId)
                if(index < 0){
                    yicuo.questions.push(timu.toObject().questions[req.params.jindu])
                    await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'yicuo'}, {questions: yicuo.questions})
                }
            }
        }
        if(result){res.send({status:200, message: '题目更新成功'})}
    })
    //  查找用户自己的错题库，如果没有错题库就新建一个
    async function collectionTitle(req){
        let yicuo = await Wxsquestion.findOne({
            openid: req.user.openid, 
            chexing: req.user.chexing, 
            kemu: req.user.kemu, 
            model: 'yicuo'
        })
        if(!yicuo){
            let yicuoQuestion = await noIsCreate(req.user, 'yicuo')
            yicuo = await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'yicuo'}, {questions: []}, {new: true})
        }
        return yicuo
    }
    // 收藏题目，或者删除收藏
    route.post('/changecollect/:jindu/:shoucang/:model', async (req, res) => {
        console.log('接收到了客户端的收藏请求')
        // 寻找错题库 没有找到就新建一个
        const yicuo = await collectionTitle(req)
        // 从用户自己的题库中找到选中的要收藏或取消收藏的题目
        const timu = await Wxsquestion.findOne({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'shunxu'})
        timu.toObject()
        yicuo.toObject()
        timu.questions[req.params.jindu].shoucang = req.params.shoucang
        console.log(timu.questions[req.params.jindu], req.params.jindu)
        await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model:'shunxu'}, {questions:timu.questions}, {new: true})
        if(req.params.shoucang == 'shoucang'){
            // 添加易错库
            timu.questions[req.params.jindu].candianji = true
            timu.questions[req.params.jindu].useranswer = ''
            timu.questions[req.params.jindu].showAnswer = false
            timu.questions[req.params.jindu].activeA = ''
            timu.questions[req.params.jindu].activeB = ''
            timu.questions[req.params.jindu].activeC = ''
            timu.questions[req.params.jindu].activeD = ''
            timu.questions[req.params.jindu].activeY = ''
            timu.questions[req.params.jindu].activeN = ''
            yicuo.questions.push(timu.questions[req.params.jindu])
            await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'yicuo'}, {questions: yicuo.questions})
        }else{
            // 从易错库中移除
            const index = yicuo.questions.findIndex(item => item.questionId == timu.questions[req.params.jindu].questionId)
            if(index > -1) {yicuo.questions.splice(index, 1)}
            await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'yicuo'}, {questions: yicuo.questions})
        }
    })
    // 从错题库中移除一个题目
    route.post('/removequestion/:jindu', async (req, res) => {
        let timu = await Wxsquestion.findOne({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'yicuo'})
        timu.toObject()

        // 删除这个题目的收藏
        const shunxu = await Wxsquestion.findOne({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'shunxu'})
        const index = timu.questions[req.params.jindu].questionId
        shunxu.toObject()
        shunxu.questions[index].shoucang = 'shoucang-copy-copy'
        await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model:'shunxu'}, {questions:shunxu.questions}, {new: true})

        //从错题集中移除
        timu.questions.splice(req.params.jindu, 1)
        await Wxsquestion.findOneAndUpdate({openid: req.user.openid, chexing: req.user.chexing, kemu: req.user.kemu, model: 'yicuo'}, {questions: timu.questions})
    })
    // 更新用户进度
    route.post('/updatejindu/:jindu/:model', async (req, res) => {
        let result = null
        if(req.params.model == 'study'){
            const result = await Wxsquestion.findOneAndUpdate({
                openid: req.user.openid, 
                chexing: req.user.chexing, 
                kemu: req.user.kemu, 
                model: 'shunxu'
            },{studyJindu: req.params.jindu})
        }else{
            const result = await Wxsquestion.findOneAndUpdate({
                openid: req.user.openid, 
                chexing: req.user.chexing, 
                kemu: req.user.kemu, 
                model: req.params.model
            },{jindu: req.params.jindu})
        }
        if(result){res.send({status:200, message: '用户进度更新成功'})}
    })
    // 更新正确或者错误总数
    route.post('/updaterighttotal/:content/:model', async (req, res) => {
        const result = await Wxsquestion.findOneAndUpdate({
            openid: req.user.openid, 
            chexing: req.user.chexing, 
            kemu: req.user.kemu, 
            model: req.params.model
        },{[req.params.content]: req.body.no})
        if(result){res.send({status:200, message: '正确错误总数更新成功'})}
    })
    // 更新用户头像和昵称
    route.post('/updateuserinfo', async (req, res) => {
        await Wxsuser.findOneAndUpdate({openid: req.user.openid}, req.body.user)
    })

    //  发表问大家
    route.post('/publishask', async (req, res) => {
        console.log(1231)
        const userId = (await Wxsuser.findOne({openid: req.user.openid}))._id
        const result = await Wxsask.create({
            userId: userId,
            content: req.body.content
        })
        if(result){res.send({status: 200, message: 'success'})}
    })
    // 根据页码获取问大家列表
    route.post('/getasklist', async (req, res) => {
        let asklist = await Wxsask.find().populate('userId').populate('comment')
        asklist = asklist.reverse()
        asklist = asklist.splice((req.body.loadingPage - 1) * 10, 10)
        if(asklist.length == 0){
            return res.send({status: 200, message: 'nomore'})
        }else{
            res.send({status: 200, message: 'success', asklist: asklist})
        }
    })
    //  添加评论
    route.post('/addcomment', async (req, res) => {
        const ask = await Wxsask.findById(req.body.reply.askId).lean()
        const result = await Wxscomment.create({
            askId: req.body.reply.askId,
            commentUserId: req.body.reply.commentUserId,
            commentContent: req.body.reply.commentContent,
            commentUserName: req.body.reply.commentUserName,
            responseUserName: req.body.reply.responseUserName
        })
        ask.comment.push(result._id)
        await Wxsask.findByIdAndUpdate(req.body.reply.askId, {comment: ask.comment})
        console.log(ask, result)
        res.send({status: 200, message: 'success'})
    })
    //  点赞 取消点赞
    route.post('/dianzan/:model', async (req, res) => {
        const Model = require(`../../models/${req.params.model}`)
        const ask = await Model.findById(req.body.model.askId).lean()
        
        if(req.body.model.type == 'add'){
            ask.like.push(req.body.model.commentUserId)
        }else{
            console.log(ask.like.findIndex)
            const index = ask.like.findIndex(item => req.body.model.commentUserId == item)
            console.log(index)
            ask.like.splice(index, 1)
        }
        const result = await Model.findByIdAndUpdate(req.body.model.askId, {like: ask.like}, {new: true})
        if(result){res.send({status: 200, message:'success'})}

    })
    //  获取问题详情
    route.post('/getaskinfo', async(req, res)=>{
        const ask = await Wxsask.findById(req.body.id).populate('comment userId').populate('comment.commentUserId').lean()
        // await Promise.all(model.comment.map(item => Comment.findById(item).populate('commentUserId').populate('comment.responseUserId comment.responseWhoId')))
        const users = await Promise.all(ask.comment.map(item => Wxsuser.findById(item.commentUserId)))
        users.map((item, index) => ask.comment[index].commentUserId = item)
        console.log(ask)
        res.send(ask)
    })
    //  更新用户合格成绩
    route.post('/updateusermoni', async (req, res) => {
        const user = await Wxsuser.findOne({openid: req.body.code}).lean()
        user.moni.push({time: req.body.time, score: req.body.score})
        Wxsuser.findOneAndUpdate({openid: req.body.code}, {moni: user.moni})
    })
    //  删除内容
    route.post('/deletecontent/:model', async(req, res)=>{
        const Model = require(`../../models/${req.params.model}`)
        await Model.findOneAndRemove({_id: req.body.id})
        res.send({status: 200, message: 'success'})
    })
    app.use('/wx/api', openid, route)
}